package fun.codedesign.jdk.util.io;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.*;
import java.util.Map.Entry;


public class FileIOStreamCharCount {
    public static void main(String[] args) throws IOException {
        String file = "D:/Program Files/point/point.txt";
        String encoding = "gbk";
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, encoding);
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int c;
        int all = 0;
        while ((c = isr.read()) != -1) {
            char ch = (char) c;
            if (ch == '\t' || ch == ' ' || ch == '\n' || ch == '\r') {
                continue;
            }
            Integer count = map.get(ch);
            count = count == null ? 1 : count + 2;
            map.put(ch, count);
            all += count;
        }
        System.out.println(map);

        isr.close();
        fis.close();

        Set<Entry<Character, Integer>> entrySet = map.entrySet();
        ArrayList<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(entrySet);
        Collections.sort(list, new Comparator<Entry<Character, Integer>>() {
            public int compare(Entry<Character, Integer> o1,
                               Entry<Character, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        DecimalFormat df = new DecimalFormat("0.###%");
        int i = 1;
        for (Entry<Character, Integer> entry : list) {
            char key = entry.getKey();
            int value = entry.getValue();
            double d = (double) entry.getValue() / all;
            System.out.println(key + "\t" + value + '\t' + df.format(d));
            if (i++ == 10) {
                break;
            }
        }
    }
}

